package com.fankui.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fankui.serviceedu.entity.EduSubject;
import com.fankui.serviceedu.entity.excel.SubjectData;
import com.fankui.serviceedu.entity.subject.OneSubject;
import com.fankui.serviceedu.entity.subject.TwoSubject;
import com.fankui.serviceedu.listener.SubjectExcelListener;
import com.fankui.serviceedu.mapper.EduSubjectMapper;
import com.fankui.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 范奎
 * @since 2023-11-23
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        // 查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);
        // 查询所有二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);
        List<OneSubject> subjectList = new ArrayList<>();
        // 封装一级分类
        for (EduSubject eduSubjectOne : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubjectOne, oneSubject);
            // 封装二级分类
            List<TwoSubject> twoSubjects = new ArrayList<>();
            for (EduSubject eduSubjectWwo : twoSubjectList) {
                if (eduSubjectWwo.getParentId().equals(eduSubjectOne.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(eduSubjectWwo, twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
            subjectList.add(oneSubject);
        }
        return subjectList;
    }
}
